package cn.smbms.controller.user;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;


import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.role.RoleServiceImpl;
import cn.smbms.service.user.UserService;
import cn.smbms.service.user.UserServiceImpl;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;


@Controller
@RequestMapping("/user")
public class UserController {
	@Resource(name="UserService")
	private UserService userService;
	@Resource(name="RoleService")
	private RoleService roleService;
	Logger log=Logger.getLogger(UserController.class);
	
	
	
	@RequestMapping(value="login",method=RequestMethod.GET )
	public ModelAndView login(@RequestParam(value="message",required=false)String message,HttpSession session ){
		ModelAndView mav=new ModelAndView();
			if(message.equals("out")){
				session.invalidate();
			}
			mav.setViewName("login");
		   return mav;
    }
	@RequestMapping(value="login",method=RequestMethod.POST)
	public ModelAndView loginUser(User user,HttpSession session){
			ModelAndView mav=new ModelAndView();
			
			User u=userService.login(user);
			if(u!=null){
				session.setAttribute("admin",u);
				mav.setViewName("frame");
			}else{
				mav.addObject("error", "用户名或密码不正确!");
				mav.setViewName("login");
			}
			
		   return mav;
    }
	
	@RequestMapping(value="useradd",method=RequestMethod.GET)
	public String register( @ModelAttribute("user")User user){
		
		
	   return "useradd";
    }
	@RequestMapping(value="useradd",method=RequestMethod.POST)
	public ModelAndView registerSave( User user,@RequestParam(value="picid" ,required=false)MultipartFile attach,
			             HttpServletRequest request){
		ModelAndView mav=new ModelAndView();
		String idPicPath = null;
		//判断文件是否为空
		
			if(!attach.isEmpty()){
				String path = request.getSession().getServletContext()
						.getRealPath("static"+File.separator+"uploadfiles");
				String oldFileName=attach.getOriginalFilename();//得到之前的名称
				String prefix=FilenameUtils.getExtension(oldFileName);//文件后缀
				//设置上传大小
			    int fileSize=500000;
				if(attach.getSize()>fileSize){
					request.setAttribute("uploadFileError", "上传文件大小不要超过500KB");
					mav.setViewName("useradd");
					return mav;
				}else {
					//判断后缀
					if (prefix.equals("jpg")||
						prefix.equals("png")||
						prefix.equals("gif")) {
						//新的文件名
						String fileName=System.currentTimeMillis()+
								RandomUtils.nextInt(100000)+"_pic."+prefix;
						//
						File targetFile=new File(path,fileName);
						if (!targetFile.exists()) {
							targetFile.mkdirs();
						} 
						//保存
						try {
							attach.transferTo(targetFile);
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
							request.setAttribute("uploadFileError", "上传失败");
							mav.setViewName("useradd");
							 return mav;
						}
						idPicPath=path+File.separator+fileName;
						
					} else {
						request.setAttribute("uploadFileError", "上传图片格式不正确");
						mav.setViewName("useradd");
						return mav;
					}
					
				}
				
			}
		
		user.setCreatedBy(1);
		user.setCreationDate(new Date());
		user.setPic(idPicPath);
		Boolean flag= userService.add(user);
		if(flag){
			mav.setViewName("userlist");
		}else{
			mav.setViewName("useradd");
		}
		
	   return mav;
     }
	@RequestMapping(value="userlist")
	public ModelAndView userList(@RequestParam(value="queryUserName",required=false)String queryUserName,
			@RequestParam(value="queryUserRole",required=false) String queryUserRole,
			@RequestParam(value="pageIndex",required=false)String pageIndex,HttpServletRequest request){
		ModelAndView mav=new ModelAndView();
		int _queryUserRole = 0;
		
		List<User> userList = null;
		//设置页面容量
    	int pageSize = Constants.pageSize;
    	//当前页码
    	int currentPageNo = 1;
		if (queryUserName==null) {
			queryUserName="";
		} 
		
		
		if(queryUserRole!= null && !queryUserRole.equals("")){
			_queryUserRole = Integer.parseInt(queryUserRole);
		}
		if (pageIndex==null) {
			pageIndex="";
		} 
    	if(pageIndex != null &&!"".equals(pageIndex)){
    		try{
    			currentPageNo = Integer.valueOf(pageIndex);
    		}catch(NumberFormatException e){
    			mav.setViewName("redirect:/user/syserror.html");
    			return mav;
    		}
    		
    	}	
    	//总数量（表）
    	int totalCount= userService.getUserCount(queryUserName,_queryUserRole);
    		
        	
    	//总页数
    	PageSupport pages=new PageSupport();
    	pages.setCurrentPageNo(currentPageNo);
    	pages.setPageSize(pageSize);
    	pages.setTotalCount(totalCount);
    	
    	int totalPageCount = pages.getTotalPageCount();
    	
    	//控制首页和尾页
    	if(currentPageNo < 1){
    		currentPageNo = 1;
    	}else if(currentPageNo > totalPageCount){
    		currentPageNo = totalPageCount;
    	}
		
		userList = userService.getUserList(queryUserName,_queryUserRole,currentPageNo, pageSize);

		
		
		
		mav.addObject("userList", userList);
		List<Role> roleList = null;
		
		roleList = roleService.getRoleList();
		mav.addObject("roleList", roleList);
		mav.addObject("queryUserName", queryUserName);
		mav.addObject("queryUserRole", queryUserRole);
		mav.addObject("totalPageCount", totalPageCount);
		mav.addObject("totalCount", totalCount);
		mav.addObject("currentPageNo", currentPageNo);
		mav.setViewName("userlist");
		 return mav;
	}
	@RequestMapping(value="getRolelist",method=RequestMethod.GET,produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public Object getRolelist(){
        List<Role> roleList = null;
		roleList = roleService.getRoleList();
		
		return JSONArray.toJSONString(roleList);
	}
	@RequestMapping("/ucexist.html")
	@ResponseBody
	public Object userCodeIsExit(@RequestParam(value="userCode")String userCode){
		Map<String, String> map=new HashMap<String, String>();
	
		String code=userCode.trim();
		User u=userService.selectUserCodeExist(code);
		if (StringUtils.isEmpty(userCode)) {
			map.put("userCode", "existEmpty");
		}else{
			if (u==null) {
				map.put("userCode", "noexist");
			} else {
	           map.put("userCode", "exist");
			}
		}
		return JSONArray.toJSONString(map);
	}	
}
